package com.mf.all.handlers;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author: lmf
 * @Create: 2025/4/4 22:47
 * @module 用于数据库中json格式集合在和java中集合的转换
 */
public class ListTypeHandler<T> extends BaseTypeHandler<List<T>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<T> parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setString(i, JSON.toJSONString(parameter));
        } catch (Exception e) {
            throw new SQLException("Error setting parameter", e);
        }
    }

    @Override
    public List<T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        try {
            String json = rs.getString(columnName);
            if (json != null) {
                return JSON.parseObject(json, new TypeReference<List<T>>() {
                });
            }
        } catch (Exception e) {
            throw new SQLException("Error getting result", e);
        }
        return null;
    }

    @Override
    public List<T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        try {
            String json = rs.getString(columnIndex);
            if (json != null) {
                return JSON.parseObject(json, new TypeReference<List<T>>() {
                });
            }
        } catch (Exception e) {
            throw new SQLException("Error getting result", e);
        }
        return null;
    }

    @Override
    public List<T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        try {
            String json = cs.getString(columnIndex);
            if (json != null) {
                return JSON.parseObject(json, new TypeReference<List<T>>() {
                });
            }
        } catch (Exception e) {
            throw new SQLException("Error getting result", e);
        }
        return null;
    }
}
